package com.jprocms.module.cms.controller.directive;

import com.jprocms.module.cms.dal.dataobject.channel.ChannelDO;
import com.jprocms.module.cms.service.channel.ChannelService;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.util.FrontContextUtil;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 栏目 自定义标签
 *
 * @author jprocms
 */
public class ChannelDirective implements TemplateDirectiveModel {
    private static final String SITE_ID = "siteId";
    /**
     * 栏目路径
     */
    private static final String CHANNEL_PATH = "channelPath";
    /**
     * 栏目id
     */
    private static final String ID = "id";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        Long id = Directives.getLong(params, ID);
        ChannelDO channel;
        if (id != null) {
            channel = channelService.getChannel(id);
        } else {
            String channelPath = Directives.getString(params, CHANNEL_PATH);
            if (StringUtils.isBlank(channelPath)) {
                throw new IllegalArgumentException("Params id or channelPath is required.");
            }
            Long defSiteId = FrontContextUtil.getSiteId(env);
            Long siteId = Directives.getLong(params, SITE_ID, defSiteId);
            channel = channelService.selectByChannelPath(channelPath, siteId);
        }
        loopVars[0] = env.getObjectWrapper().wrap(channel);
        body.render(env.getOut());
    }

    private final ChannelService channelService;

    public ChannelDirective(ChannelService channelService) {
        this.channelService = channelService;
    }
}
